#include "apue.h"
#include <sys/wait.h>
#define DEF_CMD "/bin/more"

int main(int argc, char **argv) {
    int fd[2];
    FILE *fp;
    pid_t pid;
    char *cmd, *name;
    char buf[MAXLINE];
    
    if (argc != 2)
        err_quit("Usage: %s <filename>", argv[0]);

    if (pipe(fd) < 0)
        err_sys("pipe error");

    if ((pid= fork()) < 0)
        err_sys("fork error");

    if (pid > 0) {  // parent
        close(fd[0]);  // not read
        if ((fp= fopen(argv[1], "r")) == NULL)
            err_sys("fopen %s error", argv[1]);
        while (fgets(buf, MAXLINE, fp) != NULL) {
            write(fd[1], buf, strlen(buf));
        }
        if (ferror(fp))
            err_sys("fgets error");

        close(fd[1]);   //close write end of pipe for reader, or reader be block
        if (waitpid(pid, NULL, 0) < 0)
            err_sys("waitpid error");

    } else {
        close(fd[1]);
        if (fd[0] != STDIN_FILENO) {
            if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO)
                err_sys("dup2 error to stdin");

            close(fd[0]);   // dont need this after dup2
        }
        if ((cmd= getenv("more")) == NULL)
            cmd= DEF_CMD;
        if ((name= strrchr(cmd, '/')) != NULL)
            name++;
        else 
            name= cmd;

        if (execl(cmd, name, NULL) < 0) 
            err_sys("excel error for %s", cmd);
    }
    exit(0);
}
